﻿using System.Data.Entity;
using System.Data.Entity.ModelConfiguration;
using System.Data.Entity.ModelConfiguration.Conventions;
using SnippetBox.Core.Data.Models;

namespace SnippetBox.Core.Data.Context {
    public class DatabaseContext : DbContext {
        public DbSet<Snippet> Snippets { get; set; }
        public DbSet<User> Users { get; set; }
        public DbSet<Category> Categories { get; set; }
        public DbSet<Favorite> Favorites { get; set; }
        
        protected override void OnModelCreating(DbModelBuilder modelBuilder) {
            modelBuilder.Conventions.Remove<OneToManyCascadeDeleteConvention>();
            
            modelBuilder.Entity<Snippet>().Property(x => x.BodyRaw).HasColumnType("NTEXT");
            modelBuilder.Entity<Snippet>().Property(x => x.Body).HasColumnType("NTEXT");
            
            //modelBuilder.Entity<User>().Ignore(x => x.FavoritedSnippets);
            //modelBuilder.Entity<User>()
            //    .HasMany(x => x.Favorites)
            //    .WithMany(x=> x.)
            //    .Map(m => {
            //             m.ToTable("UserFavoriteSnippets");
            //             m.MapLeftKey("UserId");
            //             m.MapRightKey("SnippetId");
            //         });
            
            modelBuilder.Entity<User>().HasMany(x => x.Snippets).WithRequired(x => x.Author);

            modelBuilder.Entity<Category>().HasMany(x => x.ChildrenCategories).WithOptional(x => x.ParentCategory);
            base.OnModelCreating(modelBuilder);
        }
    }
}
